﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.IO;
using System.Linq;
using System.Xml.XPath;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    public class XapFile
    {
        private readonly string _filePath;
        public string Guid { get; private set; }
        public string Title { get; private set; }
        public string Author { get; private set; }
        public string Genre { get; private set; }
        public string Version { get; private set; }
        public string Icon { get; private set; }

        public XapFile(string file)
        {
            if (!File.Exists(file))
                throw new FileNotFoundException(file);
            _filePath = file;
            ReadManifest();
        }

        private void ReadManifest()
        {
            using (var manifestStream = GetFileStreamFromXap(@"WMAppManifest.xml"))
            {
                var deployIsolateFile = new WpDeployApplication();

                var document = new XPathDocument(manifestStream);
                var navigator = document.CreateNavigator().SelectSingleNode("//App");

                if (navigator != null)
                {
                    Guid = navigator.GetAttribute("ProductID", string.Empty).Replace("{", "").Replace("}", "");
                    Title = navigator.GetAttribute("Title", string.Empty);
                    Author = navigator.GetAttribute("Author", string.Empty);
                    Genre = navigator.GetAttribute("Genre", string.Empty);
                    Version = navigator.GetAttribute("Version", string.Empty);
                    var selectSingleNode = navigator.SelectSingleNode("//App//IconPath");
                    if (selectSingleNode != null)
                        Icon = selectSingleNode.ToString();
                    deployIsolateFile.Guid = Guid;
                    deployIsolateFile.Title = Title;
                    deployIsolateFile.RenameTitle = string.Empty;
                }
            }
        }

        private Stream GetFileStreamFromXap(string file)
        {
            MemoryStream rv = null;
            using (var zip = ZipStorer.Open(_filePath, FileAccess.Read))
            {
                var entries = zip.ReadCentralDir();
                foreach (var entry in entries.Where(entry => Path.GetFileName(entry.FilenameInZip) == file))
                {
                    rv = new MemoryStream(2048);
                    zip.ExtractFile(entry, rv);
                    rv.Seek(0, SeekOrigin.Begin);
                }
            }
            return rv;
        }

    }

}
